package aftersale

import (
	"context"
	"fmt"

	"mall/common/globalkey"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"

	// "mall/service/backend/rpc/backendclient"
	"mall/service/order/rpc/orderclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAfterSaleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 处理售后申请
func NewUpdateAfterSaleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAfterSaleLogic {
	return &UpdateAfterSaleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateAfterSaleLogic) UpdateAfterSale(req *types.AfterSaleInfo) (*types.BaseMsgResp, error) {
	if req.Id == nil || *req.Id == 0 || req.AfterSaleType == nil || *req.AfterSaleType == 0 || req.Status == nil || *req.Status == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if *req.AfterSaleType != globalkey.AfterSaleTypeRefund && *req.AfterSaleType != globalkey.AfterSaleTypeReturn && *req.AfterSaleType != globalkey.AfterSaleTypeBarter {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	res, err := l.svcCtx.OrderRpc.UpdateAfterSale(l.ctx, &orderclient.AfterSaleInfo{
		Id:               req.Id,
		AfterSaleType:    req.AfterSaleType,
		ReasonForRefusal: req.ReasonForRefusal,
		Status:           req.Status,
	})
	if err != nil {
		return nil, err
	}

	//换货 通知erp
	// if res.IsBarter != nil && *res.IsBarter {
	// 	if res.Id != nil && *res.Id > 0 {
	// 		fmt.Println("触发erp")
	// 		erp, err := l.svcCtx.OrderRpc.BackendPushAfterSaleOrderToErp(l.ctx, &orderclient.PushOrderReq{
	// 			Ids: []uint64{
	// 				*req.Id,
	// 			},
	// 		})
	// 		if err != nil {
	// 			return nil, err
	// 		}

	// 		_, err = l.svcCtx.BackendRpc.BackendPushOrderToErp(l.ctx, &backendclient.PushOrderToErpReq{
	// 			Data: erp.Data,
	// 		})
	// 		if err != nil {
	// 			return nil, err
	// 		}
	// 	}
	// }

	//退款 触发微信退款
	if res.IsRefund != nil && *res.IsRefund {
		fmt.Println("触发退款")
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
